import { getStore, setStore, removeStore } from '@/utils/store';
import Router from '@/router';
import { Toast } from 'vant';

export default {
	state: {
		token: getStore('token') || '',
		userInfo: getStore('userInfo') || {},
		isShowSearch: false,
		indexRefresh: true,
		jdShowSearch: false,
		bwbt: {
			conf: {},
			userInfo: {}
		}
	},
	actions: {
		// 第一次登录授权
		async LOGIN({ dispatch, commit }) {
			return new Promise((resolve, reject) => {
				let token = getStore('token');
				const next = token => {
					dispatch('GET_USERINFO');
					resolve();
					if (window.location.href.indexOf('flashsale') !== -1) {
						// 获取浏览器上带的类型 flashsale 作为type 跳转 到相应页面
						let type =
							decodeURIComponent(
								(new RegExp('[?|&]flashsale=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')
							) || null;
						let sdkType = getUrlParams('sdkType') || '';
						let channel = getUrlParams('channel') || '';
						let activity = getUrlParams('activity') || '';
						let commonUrl =
							'?app=yzf&sdkType=' + sdkType + '&channel=' + channel + '&activity=' + activity + '&token=' + getStore('token');

						if (type === '1') {
							this.baiduPush('外部渠道', 'tap', '进入限时抢购');
							window.location.href = 'https://zfx.xmonecode.com/' + commonUrl + '#/special-flash-sale';
						} else if (type === '2') {
							this.baiduPush('外部渠道', 'tap', '进入百亿补贴');
							// window.location.href = 'https://zfx.xmonecode.com/million/' + commonUrl + '#/';
						} else if (type === '3') {
							this.baiduPush('外部渠道', 'tap', '进入今日上新');
							window.location.href = 'https://zfx.xmonecode.com/' + commonUrl + '#/special-fresh';
						} else if (type === '4') {
							this.baiduPush('外部渠道', 'tap', '进入9.9包邮');
							window.location.href = 'https://zfx.xmonecode.com/' + commonUrl + '#/special-free';
						} else if (type === '5') {
							this.baiduPush('外部渠道', 'tap', '进入大额券');
							window.location.href = 'https://zfx.xmonecode.com/' + commonUrl + '#/special-hot';
						} else if (type === '6') {
							this.baiduPush('外部渠道', 'tap', '进入天猫国际');
							window.location.href = 'https://zfx.xmonecode.com/' + commonUrl + '#/special-tmall-global';
						} else if (type === '7') {
							this.baiduPush('外部渠道', 'tap', '进入品牌优选');
							window.location.href = 'https://zfx.xmonecode.com/' + commonUrl + '#/special-brand';
						} else if (type === '8') {
							this.baiduPush('外部渠道', 'tap', '进入0元购');
							window.location.href = 'https://zfx.xmonecode.com/' + commonUrl + '#/special-none';
						} else if (type === '9') {
							this.baiduPush('外部渠道', 'tap', '进入大转盘');
							window.location.href = 'https://zfx.xmonecode.com/lucky/' + commonUrl + '#/';
						} else if (type === '10') {
							this.baiduPush('外部渠道', 'tap', '进入付邮即送');
							this.service.common.common.selfmallLogin().then(res => {
								setStore('selfInfo', res);
								switch (process.env.NODE_ENV) {
									case 'production':
										window.location.href = 'https://zfx.xmonecode.com/#/free?token=' + getStore('token') + '&channel=' + channel;
										break;
									case 'development':
										window.location.href = 'http://192.168.0.158:8081/' + commonUrl + '#/free'; // ?token=' + getStore('token'); // commonUrl不是加了token吗，怎么还加 (⊙_⊙;)
										break;
									case 'none':
										window.location.href = 'https://zfx.xmonecode.com/#/free?token=' + getStore('token') + '&channel=' + channel;
										break;
								}
							});
						} else if (type === '11') {
							this.baiduPush('外部渠道', 'tap', '进入日历活动');
							this.service.common.common.selfmallLogin().then(res => {
								setStore('selfInfo', res);
								switch (process.env.NODE_ENV) {
									case 'production':
										window.location.href = 'https://zfx.xmonecode.com/#/today?token=' + getStore('token') + '&channel=' + channel;
										// window.location.href = `https://zfx-dev.xmonecode.com/和尚/index.html?&token=${getStore('token')}#/today`;
										break;
									case 'development':
										window.location.href = 'http://192.168.0.158:8081/' + commonUrl + '#/today?token=' + getStore('token');
										break;
								}
							});
						} else if (type === '12') {
							this.service.common.common.selfmallLogin().then(res => {
								setStore('selfInfo', res);
								const id =
									decodeURIComponent(
										(new RegExp('[?|&]' + 'id' + '=' + '([^&;]+?)(&|#|;|$)').exec(window.location.href) || [, ''])[1].replace(
											/\+/g,
											'%20'
										)
									) || null;
								switch (process.env.NODE_ENV) {
									case 'production':
										// window.location.href = `https://zfx-dev.xmonecode.com/和尚/index.html?id=${id}&token=${getStore(
										// 	'token'
										// )}#/squeeze/ticket`;
										window.location.href = `https://zfx.xmonecode.com?id=${id}&channel=${channel}&token=${getStore(
											'token'
										)}#/squeeze/ticket`;
										break;
									case 'development':
										window.location.href = `http://192.168.0.158:8081?id=${id}&channel=${channel}&token=${getStore(
											'token'
										)}#/squeeze/ticket`;
										break;
								}
							});
						}
						// else if (type === '12') {
						// 	// 通用券ID
						// 	const id =
						// 		decodeURIComponent(
						// 			(new RegExp('[?|&]' + 'id' + '=' + '([^&;]+?)(&|#|;|$)').exec(window.location.href) || [, ''])[1].replace(
						// 				/\+/g,
						// 				'%20'
						// 			)
						// 		) || null;
						// 	switch (process.env.NODE_ENV) {
						// 		case 'production':
						// 			Router.push({
						// 				path: '/squeeze/ticket'
						// 			});
						// 			// window.location.href = `https://zfx-dev.xmonecode.com/和尚/index.html?id=${id}&token=${getStore('token')}#/squeeze/ticket`;
						// 			// window.location.href = `https://zfx.xmonecode.com?id=${id}&token=${getStore('token')}#/squeeze/ticket`;
						// 			break;
						// 		case 'development':
						// 			Router.push({
						// 				path: '/squeeze/ticket'
						// 			});
						// 			// window.location.href = `http://192.168.0.158:8081?id=${id}&token=${getStore('token')}#/squeeze/ticket`;
						// 			break;
						// 	}
						// }
					}
				};
				// ios本地缓存的token为空， 所以加上这段
				let urlToken =
					decodeURIComponent(
						(new RegExp('[?|&]' + 'token' + '=' + '([^&;]+?)(&|#|;|$)').exec(window.location.href) || [, ''])[1].replace(/\+/g, '%20')
					) || null;
				if (urlToken) {
					token = urlToken;
					commit('SET_TOKEN', urlToken);
				}

				if (token && token != 'undefined') {
					return next();
				}

				// 获取翼支付授权
				let params = {
					scope: 'user_info,mobile', // 需要授权获取的内容
					clientId: '86000000162', // 第三方应用编号
					redirectUrl: 'http://zfx.xmonecode.com', // 回调地址,必须和申请应用是填写对一致
					merchantCode: '3178034478305436', // 商户号
					clientName: '一码当先', // 商户名称
					state: 'bestpay' // 第三方平台自定义参数，用户授权后会原样回传给第三方平台
				};

				window.BestpayHtml5.User.userAuth(
					params,
					res => {
						this.baiduPush('授权登录事件', 'tap', '授权成功');

						this.service.common.common
							.getYzfTokenByCode({
								code: res.code,
								grantType: res.grantType,
								refreshToken: res.refreshToken || ''
							})
							.then(res => {
								commit('SET_TOKEN', res.token);
								next();
							})
							.catch(err => {
								console.error(err);
								Toast('授权失败');
							});
					},
					err => {
						reject(err);
						// 错误处理
						this.baiduPush('授权登录事件', 'tap', '授权错误');
					},
					err => {
						reject(err);
						// 退出子应用
						this.baiduPush('授权登录事件', 'tap', '授权取消');
						window.BestpayHtml5.APP.exitSubApp();
					}
				);
			});
		},

		// 退出登录
		LOGOUT({ commit }) {
			commit('CLEAR_TOKEN');
			commit('CLEAR_USERINFO');
		},

		// 切换用户
		SWITCH({ dispatch }) {
			Toast.loading({
				message: '切换账号中',
				forbidClick: true
			});

			// 退出
			dispatch('LOGOUT');

			// 重新登录
			dispatch('LOGIN')
				.then(res => {
					console.log(res);
					Toast.clear();
					Toast('账号切换成功');
					Router.push('/');
				})
				.catch(err => {
					Toast.clear();
					Toast(err.message);
				});
		},

		// 获取用户信息
		async GET_USERINFO({ commit, dispatch, state }) {
			const userInfo = await this.service.common.user.getUserinfo({
				type: 1
			});

			console.log('百亿补贴用户信息', userInfo);

			commit('SET_USERINFO', userInfo);
		},

		async SEARCH({ commit }, flag) {
			commit('SET_SEARCH', flag);
		},

		async JDSEARCH({ commit }, flag) {
			commit('SET_JDSEARCH', flag);
		},

		// 获取百万补贴用户信息
		GET_BWBT_USERINFO({ commit }) {
			return this.service.bwbt.bwbtUser
				.getUserInfo({
					app: 'yzf',
					sdkType: 'yzf'
				})
				.then(res => {
					commit('SET_BWBT', res);
					return res;
				});
		}
	},

	mutations: {
		SET_TOKEN(state, value) {
			state.token = value;
			setStore('token', value);
		},
		CLEAR_TOKEN(state) {
			state.token = '';
			removeStore('token');
		},
		SET_USERINFO(state, value) {
			state.userInfo = value;
			setStore('userInfo', value);
		},
		CLEAR_USERINFO(state) {
			state.userInfo = {};
			removeStore('userInfo');
		},
		SET_SEARCH(state, value) {
			state.isShowSearch = value;
		},
		SET_INDEX_REFRESH(state, value) {
			state.indexRefresh = value;
		},
		SET_JDSEARCH(state, value) {
			state.jdShowSearch = value;
		},
		SET_BWBT(state, value) {
			state.bwbt = {
				conf: value.config,
				userInfo: value.user
			};
		}
	}
};
